package com.robert.cool.weather.app.service;

import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;

import com.jess.arms.base.BaseService;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.robert.cool.weather.mvp.model.api.Api;
import com.robert.cool.weather.mvp.model.api.cache.CommonCache;
import com.robert.cool.weather.mvp.model.api.service.CommonService;
import com.robert.cool.weather.mvp.model.api.service.WeatherService;
import com.robert.cool.weather.mvp.model.entity.C;
import com.robert.cool.weather.mvp.model.entity.Weather;
import com.tencent.mmkv.MMKV;

import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.rx_cache2.DynamicKey;
import io.rx_cache2.EvictProvider;
import io.rx_cache2.Reply;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;
import okhttp3.ResponseBody;
import timber.log.Timber;

public class AutoUpdateService extends BaseService {
    public AutoUpdateService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void init() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            //数字是随便写的“40”，
            nm.createNotificationChannel(new NotificationChannel("40", "App Service", NotificationManager.IMPORTANCE_HIGH));
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "40");

            //其中的2，是也随便写的，正式项目也是随便写
            startForeground(2, builder.build());
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        updateWeather();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour = 1 * 60 * 1000;//八小时
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(this, AutoUpdateService.class);
        PendingIntent pi;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            pi = PendingIntent.getForegroundService(this, 0,
                    i, PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            pi = PendingIntent.getService(this, 0,
                    i, PendingIntent.FLAG_UPDATE_CURRENT);
        }
        if (manager != null) {
            manager.cancel(pi);
            manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void updateWeather() {
        String weatherId = MMKV.defaultMMKV().decodeString(C.WeatherId);
        AppComponent appComponent = ArmsUtils.obtainAppComponentFromContext(this);
        RxErrorHandler rxErrorHandler = appComponent.rxErrorHandler();
        IRepositoryManager iRepositoryManager = appComponent.repositoryManager();
        Observable<Weather> query = iRepositoryManager.obtainRetrofitService(WeatherService.class).queryWeather(Api.QueryWeather + weatherId);
        query =  Observable.just(query).flatMap(new Function<Observable<Weather>, ObservableSource<Weather>>() {
            @Override
            public ObservableSource<Weather> apply(Observable<Weather> weatherObservable) throws Exception {
                return iRepositoryManager.obtainCacheService(CommonCache.class).queryWeather(weatherObservable,new DynamicKey(weatherId),new EvictProvider(true))
                        .map(new Function<Reply<Weather>, Weather>() {
                            @Override
                            public Weather apply(Reply<Weather> weatherReply) throws Exception {
                                return weatherReply.getData();
                            }
                        });
            }
        });
        query.subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<Weather>(rxErrorHandler) {
                    @Override
                    public void onNext(Weather weather) {
                        Timber.d("----定时请求生效---");
                    }
                });
    }
}
